package pers.jzh.std.agent.attach.attachmodule;

import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Application {

    private static final Map<String,String> classMapper = new HashMap<>();

    static {
        classMapper.put("pers.jzh.std.agent.attach.mainmodule.Application","C:\\tmp\\agent-module-1.0-SNAPSHOT.jar");
    }

    public static void main(String[] args) {
        Process process = loadProcesses("pers.jzh.std.agent.attach.mainmodule");
        if(null != process){
            try {
                VirtualMachine vm = VirtualMachine.attach(process.getPid());
                vm.loadAgent(classMapper.get(process.getName()), args.length > 2 ? args[2] : null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("cannot find process named 'pers.jzh.std.agent.attach.mainmodule'");
        }

    }


    private static Process loadProcesses(String targetName) {
        Process process = null;
        List<VirtualMachineDescriptor> descriptors = VirtualMachine.list();
        for (VirtualMachineDescriptor descriptor : descriptors) {
            String displayName = descriptor.displayName();
            String id = descriptor.id();
            System.out.println(displayName + " : " + id);
            if(displayName.contains(targetName)){
                process = new Process(id, displayName);
            }
        }
        return process;
    }

    static class Process {
        private String pid;
        private String name;

        public Process(String pid, String name) {
            this.pid = pid;
            this.name = name;
        }

        public String getPid() {
            return pid;
        }

        public String getName() {
            return name;
        }
    }

}
